package com.conversationboard.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.conversationboard.logger.LogMessageType;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

public class SecurityChecks {

	/**
	 * Perform security checks
	 * 
	 * @param request
	 * @param user
	 * @param callingObject
	 *            : pass in 'this'. Allows the class to get the classname for an
	 *            error log.
	 * @return
	 * @throws EncryptionException
	 * @throws IOException
	 */

	public static boolean passes(HttpServletRequest request, User user, Object callingObject) throws ServletException {

		try {
			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Security key check failure in : " + callingObject.getClass().getName(), user, LogMessageType.USER);
				return false;
			}

			return true;
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}
	}


	public static boolean passes(HttpServletRequest request, Object callingObject, int expiryTimeInMinutes) {

		/* Security: ensure it was conversation board that submitted this form */

		String key = request.getParameter("key");
		EncryptedKey encryptedKey = new EncryptedKey();

		if (!encryptedKey.isValid(key, expiryTimeInMinutes)) {
			return false;
		}

		return true;

	}


	public static boolean passes(HttpServletRequest request, Object callingObject) {

		/* Security: ensure it was conversation board that submitted this form */

		String key = request.getParameter("key");
		EncryptedKey encryptedKey = new EncryptedKey();

		if (!encryptedKey.isValid(key)) {
			return false;
		}

		return true;
	}

}
